//
//  Networking.m
//  IHKApp
//
//  Created by calvin on 15/4/7.
//  Copyright (c) 2015年 www.ihk.cn. All rights reserved.
//

#import "Networking.h"
#import <CommonCrypto/CommonDigest.h>



#define SERVER_API  @"http://beta.api.mypip.cn/router"
#define APP_KEY     @"JC-iOS-Beta"
#define APP_SECRET  @"NGZlYmUxNzNkOWY5Y2FhOWU4M2VjMjUz"



@implementation Networking

//get请求
+ (void)getDataWithApiName:(NSString *)apiName parameter:(NSDictionary *)dict result:(void (^)(NSDictionary *dic))success fail:(void (^)(NSError *error))fail {
    
    NSMutableDictionary *paras = [self getDictionaryWithApiName:apiName parameter:dict];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 60;
    
    [self showRequestUrl:SERVER_API paras:paras];//输出
    
    [session GET:SERVER_API parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
    

    
}

//post请求
+ (void)postDataWithApiName:(NSString *)apiName parameter:(NSDictionary *)dict result:(void (^)(NSDictionary *dic))success fail:(void (^)(NSError *error))fail {
    
    
    NSMutableDictionary *paras = [self getDictionaryWithApiName:apiName parameter:dict];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 60;
    
    [self showRequestUrl:SERVER_API paras:paras];//输出
    
    [session POST:SERVER_API parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    
    
    
}

//签名和加密
+(NSMutableDictionary *)getDictionaryWithApiName:(NSString *)apiName parameter:(NSDictionary *)dict{
    NSMutableDictionary *sysParam = [[NSMutableDictionary alloc]init];
    [sysParam setValue:APP_KEY forKey:@"appKey"];
    [sysParam setValue:@"json" forKey:@"format"];
    [sysParam setValue:@"1.0.0" forKey:@"v"];
    [sysParam setValue:[NSString stringWithFormat:@"%.0f", [[NSDate date] timeIntervalSince1970]*1000.f] forKey:@"timestamp"];
    [sysParam setValue:apiName forKey:@"apiName"];
    
    [sysParam setValue:@"716b306330a541cd81b4ab6b96781189" forKey:@"session"];
    
    static NSString * const secret = APP_SECRET;
    NSMutableDictionary *tmp = [NSMutableDictionary new];
    [tmp addEntriesFromDictionary:sysParam];
    [tmp addEntriesFromDictionary:dict];
    
    NSMutableArray *tmpKeys = [[tmp allKeys] mutableCopy];
    [tmpKeys sortUsingComparator:^NSComparisonResult(NSString * _Nonnull obj1, NSString * _Nonnull obj2) {
        return strcmp([obj1 UTF8String] , [obj2 UTF8String]) < 0 ? NSOrderedAscending : NSOrderedDescending;
    }];
    
    NSMutableString *sign = [NSMutableString new];
    [sign appendString:secret];
    for (NSString *key in tmpKeys){
        id tmpVal = [tmp objectForKey:key];
        if ([tmpVal isKindOfClass:[NSArray class]] || [tmpVal isKindOfClass:[NSDictionary class]]){
            NSData *tmpData = [NSJSONSerialization dataWithJSONObject:tmpVal options:0 error:nil];
            tmpVal = [[NSString alloc] initWithData:tmpData encoding:NSUTF8StringEncoding];
        }
        if ([tmpVal isKindOfClass:[NSString class]]){
            tmpVal = [(NSString *)tmpVal stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
        }
        [sign appendFormat:@"%@%@", key, tmpVal];
    }
    [sign appendString:secret];
    
    
    sysParam[@"sign"] = [self getmd5:sign];
    
    //    字典转字符串
    NSData *sysData = [NSJSONSerialization dataWithJSONObject:sysParam options:0 error:nil];
    NSString *sys = [[NSString alloc] initWithData:sysData encoding:NSUTF8StringEncoding];
    
    
    NSMutableDictionary *bizParam = [[NSMutableDictionary alloc]init];
    [bizParam addEntriesFromDictionary:dict];
    //    字典转字符串
    NSData *bizData = [NSJSONSerialization dataWithJSONObject:bizParam options:0 error:nil];
    NSString *biz = [[NSString alloc] initWithData:bizData encoding:NSUTF8StringEncoding];
    
    
    NSMutableDictionary *paras = [[NSMutableDictionary alloc]init];
    [paras setValue:biz forKey:@"bizParam"];
    [paras setValue:sys forKey:@"sysParam"];
    
    return paras;
}



+(NSString *)getmd5:(NSString *)str
{
    //DONE:md5加密
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


+ (void)showRequestUrl:(NSString *)serverUrl paras:(NSMutableDictionary *)paras {
    NSString *url = @"";
    for (NSString *keyName in paras) {
        url = [[[[url stringByAppendingString:@"&"] stringByAppendingString:keyName]stringByAppendingString:@"="]stringByAppendingString:[NSString stringWithFormat:@"%@",[paras objectForKey:keyName]]];
    }
    url = [url substringFromIndex:1];
    url = [[serverUrl stringByAppendingString:@"?"]stringByAppendingString:url];
    NSLog(@"requestUrl:%@",url);
}


@end
